package main

import (
	"sync"
	"time"
)

type CallCounter struct {
	mu        sync.Mutex
	calls     []time.Time
	interval  time.Duration
	maxWindow int
}

func NewCallCounter(interval time.Duration, maxWindow int) *CallCounter {
	return &CallCounter{
		interval:  interval,
		maxWindow: maxWindow,
	}
}

func (cc *CallCounter) AddCall() {
	cc.mu.Lock()
	defer cc.mu.Unlock()

	// 移除超出时间窗口的调用记录
	now := time.Now()
	for len(cc.calls) > 0 && now.Sub(cc.calls[0]) > cc.interval {
		cc.calls = cc.calls[1:]
	}

	// 添加当前调用时间到列表
	cc.calls = append(cc.calls, now)
}

func (cc *CallCounter) ShouldReturnTrue() bool {
	cc.mu.Lock()
	defer cc.mu.Unlock()

	callCount := len(cc.calls)

	// 如果调用次数达到100次，返回true，并清空调用记录
	if callCount >= cc.maxWindow {
		cc.calls = nil
		return true
	}

	return false
}
func monitorPostErr() {
	monitorCounter.AddCall()
	if monitorCounter.ShouldReturnTrue() {
		rs := []int{}
		bDlock.RLock()
		for k, v := range bDmap {
			if v.roomid != 0 {
				rs = append(rs, k)
			}
		}
		bDlock.RUnlock()
		//fmt.Println("调用了100次")
		postMonitorErr(100, len(rs))
	}
}

var monitorCounter *CallCounter

func init() {
	monitorCounter = NewCallCounter(10*time.Minute, 100) // 设置时间窗口为10分钟，每100次返回一次true
}
